package com.miage.kangourou.server.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.miage.kangourou.client.beans.Promo;


public class PromoDao extends GenericDao<Promo> {

	public PromoDao(Connection connect) {
		super(connect);
	}

	public Promo findById(int id) throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM PROMO WHERE ID_PROMO = " + id);

		Promo promo;

		if (result.next()) {
			promo = new Promo(result.getInt("ID_PROMO"), result
					.getString("INTITULE"), result.getString("EMAIL"));
		} else {
			promo = new Promo();
		}

		result.close();

		return promo;
	}

	public List<Promo> findAll() throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM PROMO");

		List<Promo> all = new ArrayList<Promo>();
		while (result.next()) {
			all.add(new Promo(result.getInt("ID_PROMO"), result
					.getString("INTITULE"), result.getString("EMAIL")));
		}

		result.close();

		return all;
	}

	public void create(Promo promo) throws SQLException {
		if (promo instanceof Promo && !promo.equals(null)) {

			connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"INSERT INTO PROMO (ID_PROMO, INTITULE, EMAIL) VALUES ("
							+ promo.getId_promo() + ", \""
							+ promo.getIntitule() + "\", \"" + promo.getEmail()
							+ "\")");
		}
	}

	public boolean alreadyExist(Promo promo) throws SQLException {
		boolean exist = false;

		if (promo instanceof Promo && !promo.equals(null)) {

			ResultSet result = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"SELECT * FROM PROMO WHERE ID_PROMO = "
							+ promo.getId_promo());

			if (result.next()) {
				exist = true;
			}

			result.close();
		}

		return exist;
	}

	public boolean delete(int idPromo){
		boolean deleted = true;

		try {
			connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY)
					.executeQuery(
							"DELETE FROM PROMO WHERE ID_PROMO = "
							+ idPromo);
		} catch (SQLException e) {
			e.printStackTrace();
			deleted = false;
		}

		return deleted;
	}

}
